<template>
  <div :style="{width: width, height: height, border: border}">
    <iframe ref="etherpadIframe" :src="src" style="width: 100%;height: 100%;"></iframe>
  </div>
</template>

<script>
  export default {
    props: {
      config: {
        type: Object,
        default: () => {
          return {};
        },
        required: true
      },
      width: {
        type: String,
        default: '100%'
      },
      height: {
        type: String,
        default: '600px'
      },
      border: {
        type: String,
        default: 'none'
      }
    },
    data() {
      return {
        src: '',
      };
    },
    computed: {
      computedConfig() {
        return Object.assign({
            ETHERPAD_APIKEY: '',
            id: new Date().getTime(), // 文档的ID
            host: 'http://192.168.10.150', // node服务地址
            baseUrl: '/p/', // 路径
            showControls: true, // 是否显示控件
            showChat: true, // 是否显示聊天按钮
            showLineNumbers: false, // 是否显示行号
            userName: '匿名', // 用户名
            useMonospaceFont: false, // 使用等宽字体
            noColors: false, // 禁用用户的文本背景色
            userColor: false, // 当前用户的文本背景色,eg. #f00f00
            hideQRCode: false, // 隐藏二维码
            alwaysShowChat: false, // 始终显示聊天框
            plugins: {}, // 与插件相关的选项，与基本的Etherpad配置无关
            rtl: false, // 从右向左显示文本
          },
          this.config
        );
      },
    },
    mounted() {
      var iframeElment = this.$refs.etherpadIframe
      if (iframeElment) {
        iframeElment.allow = 'microphone;camera;midi;encrypted-media;'
      }
      this.src =
        `${this.computedConfig.host}${this.computedConfig.baseUrl}${this.computedConfig.id}?showControls=${this.computedConfig.showControls}&showChat=${this.computedConfig.showChat}&showLineNumbers=${this.computedConfig.showLineNumbers}&userMonospaceFont=${this.computedConfig.useMonospaceFont}&userName=${this.computedConfig.userName}&noColors=${this.computedConfig.noColors}&userColor=${this.computedConfig.userColor}&hideQRCode=${this.computedConfig.hideQRCode}&alwaysShowChat=${this.computedConfig.alwaysShowChat}&rtl=${this.computedConfig.rtl}`;
    },
    methods: {
      service({
        url,
        method = "GET",
        params = {},
        data = {}
      }) {
        return new Promise((resolve, reject) => {
          method = method.toUpperCase()
          let queryString = "";
          Object.keys(params).forEach(key => {
            queryString += `${key}=${params[key]}&`;
          });

          if (queryString) {
            queryString = queryString.substring(0, queryString.length - 1);
            url += "?" + queryString;
          }

          const request = new XMLHttpRequest();

          request.open(method, url, true);
          if (method === "GET") {
            request.send();
          } else if (method === "POST") {
            request.setRequestHeader(
              "Content-Type",
              "application/json;charset=utf-8"
            );
            request.send(JSON.stringify(data)); // 发送JSON格式的请求体参数
          }

          request.onreadystatechange = function() {
            if (request.readyState !== 4) {
              return;
            }
            const {
              status,
              statusText
            } = request;
            if (status >= 200 && status < 300) {
              const response = {
                data: JSON.parse(request.response),
                status,
                statusText
              };
              resolve(response);
            } else {
              reject(new Error("request error status is " + status));
            }
          };
        });
      },
      getDownloadUrl(){
        return `${this.computedConfig.host}${this.computedConfig.baseUrl}${this.computedConfig.id}/export/pdf`
      },
      setContent(content) {
        this.service({
          url: `${this.computedConfig.host}/api/1/setText`,
          method: 'POST',
          data: {
            padID: this.computedConfig.id,
            apikey: this.computedConfig.ETHERPAD_APIKEY,
            text: content
          }
        }).then(
          response => {
            // console.log(response);
          },
          error => {
            console.log(error.message);
          }
        );
      },
      setHtml(content) {
        this.service({
          url: `${this.computedConfig.host}/api/1/setHTML`,
          method: 'POST',
          data: {
            padID: this.computedConfig.id,
            apikey: this.computedConfig.ETHERPAD_APIKEY,
            html: content
          }
        }).then(
          response => {
            // console.log(response);
          },
          error => {
            console.log(error.message);
          }
        );
      },
      appendContent(content) {
        this.service({
          url: `${this.computedConfig.host}/api/1/getText`,
          method: 'GET',
          params: {
            padID: this.computedConfig.id,
            apikey: this.computedConfig.ETHERPAD_APIKEY
          }
        }).then((res) => {
          this.setContent(`${res.data.data.text}${content}`)
        });
      },
      getContent() {
        return new Promise((reslove, reject) => {
          this.service({
            url: `${this.computedConfig.host}/api/1/getText`,
            method: 'GET',
            params: {
              padID: this.computedConfig.id,
              apikey: this.computedConfig.ETHERPAD_APIKEY
            }
          }).then((res) => {
            reslove(res.data.data)
          });
        })
      },
      getHtml() {
        return new Promise((reslove, reject) => {
          this.service({
            url: `${this.computedConfig.host}/api/1/getHTML`,
            method: 'GET',
            params: {
              padID: this.computedConfig.id,
              apikey: this.computedConfig.ETHERPAD_APIKEY
            }
          }).then((res) => {
            reslove(res.data.data)
          });
        })
      }
    }
  };
</script>

<style></style>
